﻿using JYH.Win.Public;
using JYH.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JYH.Model;
using Newtonsoft.Json;
using JYH.Model.API;
using System.Net.Http.Headers;
using System.Net.Http;
using System.IO;
using FastReport;
using FastReport.Export.Dbf;

namespace JYH.Win.Smart
{
    public partial class FormMaterialCounting : FormBase
    {
        public FormMaterialCounting()
        {
            InitializeComponent();
        }
        public List<BasBarcodeInfo> BarcodeInfos = new List<BasBarcodeInfo>();
        ApiClient apiClient = new ApiClient();
        public string Msg=string.Empty;

        SerialPortHelper sp = new SerialPortHelper();
        public string ComName { get; set; } = "COM1";

        private void InitData()
        {
            if (ConfigHelper.CheckAppSettingKey("WebAPIServer"))
            {
                this.Url = ConfigHelper.GetValue("WebAPIServer");
            }
        }

        private async void txtBarcodeNO_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BasBarcodeInfo data = new BasBarcodeInfo();
                data.BarcodeNO = txtBarcodeNO.Text;

                try
                {
                    var response = await apiClient.PostAsync(Url + "/api/WIN/GetSingleBarcode", data);
                    object obj = JsonConvert.DeserializeObject(response);


                    // 重新序列化为不带转义符的字符串

                    ResponseJson<BasBarcodeInfo> res = JsonConvert.DeserializeObject<ResponseJson<BasBarcodeInfo>>(obj.ToString());
                    if (res != null && res.Items != null && res.Items.Count > 0)
                    {
                        data = res.Items[0];
                        txtMaterialNO.Text = data.MaterialNO;
                        txtMaterialNO.ReadOnly = true;
                        txtMaterialDesc.Text = data.MaterialDesc;
                        txtMaterialDesc.ReadOnly = true;
                        txtMaterialName.Text = data.MaterialName;
                        txtMaterialName.ReadOnly = true;
                        txtBatchNO.Text = data.BatchNO;
                        if (!string.IsNullOrEmpty(txtBatchNO.Text))
                        {
                            txtBatchNO.ReadOnly = true;
                        }



                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }
            }
        }

        private async void txtMaterialNO_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) 
            {
                BasMaterialInfo data = new BasMaterialInfo();
                data.MaterialNO= txtMaterialNO.Text;

                try
                {
                    var response = await apiClient.PostAsync(Url + "/api/WIN/GetSingleMaterial", data);
                    object obj = JsonConvert.DeserializeObject(response);


                    // 重新序列化为不带转义符的字符串

                    ResponseJson<BasMaterialInfo> res = JsonConvert.DeserializeObject<ResponseJson<BasMaterialInfo>>(obj.ToString());
                    if (res != null && res.Items != null && res.Items.Count > 0)
                    {
                        data=res.Items[0];
                        txtMaterialDesc.Text = data.MaterialDesc;
                        txtMaterialDesc.ReadOnly = true;
                        txtMaterialName.Text = data.MaterialName;
                        txtMaterialName.ReadOnly = true;


                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }
            }
        }

        private async void txtQty_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) 
            {
                if (string.IsNullOrEmpty(txtQty.Text))
                {
                    MessageBox.Show("Please Input Quantity");
                    return;
                }
                if (string.IsNullOrEmpty(txtMaterialNO.Text))
                {
                    MessageBox.Show("Please Input Part NO");
                    return;
                }
                if (string.IsNullOrEmpty(txtBatchNO.Text))
                {
                    MessageBox.Show("Please Input Lot NO");
                    return;
                }

                dgvMain.DataSource = null;
                BasBarcodeInfo data = new BasBarcodeInfo();
                data.MaterialNO = txtMaterialNO.Text;
                data.BatchNO = txtBatchNO.Text;
                decimal qty = 0;
                decimal.TryParse(txtQty.Text,out qty);
                data.Qty = qty;
                data.Quantity = 1;
                data.PackQty = qty;
                data.CreateUser = this.CurrentUser.UserNO;

                try
                {
                    var response = await apiClient.PostAsync(Url + "/api/WIN/AddNewwBarcode", data);
                    object obj = JsonConvert.DeserializeObject(response);


                    // 重新序列化为不带转义符的字符串

                    ResponseJson<BasBarcodeInfo> res = JsonConvert.DeserializeObject<ResponseJson<BasBarcodeInfo>>(obj.ToString());
                    if (res != null && res.Items != null && res.Items.Count > 0)
                    {
                        data = res.Items[0];
                        BarcodeInfos.Insert(0,data);
                        dgvMain.DataSource = BarcodeInfos;
                        txtMaterialDesc.Text ="";
                        txtMaterialDesc.ReadOnly = true;
                        txtMaterialName.Text ="";
                        txtMaterialName.ReadOnly = true;
                        txtBarcodeNO.Text = "";
                        txtMaterialNO.Text = "";
                        txtBatchNO.Text = "";
                        txtBatchNO.ReadOnly = false;
                        txtBarcodeNO.ReadOnly = false;
                        txtMaterialNO.ReadOnly = false;
                        txtBarcodeNO.Focus();
                        GetPrint(sender, e);

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }

            }
        }

        private void FormMaterialCounting_Load(object sender, EventArgs e)
        {
            dgvMain.AutoGenerateColumns = false;
           
            if (ConfigHelper.CheckAppSettingKey("ComName"))
            {
                ComName = ConfigHelper.GetValue("ComName");
            }
      
            serialPort1.PortName = ComName;
            try
            {
                serialPort1.Open();
            }
            catch 
            { }
   
        }

        private delegate void DataDelegate(byte[] buffer);

        private  void GetRecod(byte[] ResBytes)
        {
            try
            {
               string Data = SerialData.ToString(ResBytes);
                txtQty.Text = Data;
                 this.txtQty_KeyUp(new object(), new KeyEventArgs(Keys.Enter));
            }
            catch
            {
            }


        }

        private void txtBarcodeNO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                string[] Strs = txtBarcodeNO.Text.Trim().Split(new char[] {'|','|'});
                txtBarcodeNO.Text = Strs[0];

               // txtBarcodeNO.Clear();
            }
        }



        private async void GetPrint(object sender, EventArgs e)
        {
            try
            {
                HttpClient _client = new HttpClient();
                List<BasBarcodeInfo> list = new List<BasBarcodeInfo>();
                if (BarcodeInfos.Count > 0)
                {
                    list.Add(BarcodeInfos[0]);
                    _client.BaseAddress =  new Uri(this.Url);
                    _client.DefaultRequestHeaders.Accept.Clear();
                    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var json = JsonConvert.SerializeObject(list);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await _client.PostAsync("/api/WIN/PrintWithFastReport", content);
                    if (response.IsSuccessStatusCode)
                    {
                        string Json = await response.Content.ReadAsStringAsync();
                        object obj = JsonConvert.DeserializeObject(Json);
           
                        ApiResponse result = JsonConvert.DeserializeObject<ApiResponse>(obj.ToString());
                        DataSet ds= JsonConvert.DeserializeObject<DataSet>(result.Data);
                        byte[] reportBytes = Convert.FromBase64String(result.ReportData);
                        //var result = await response.Content.ReadAsByteArrayAsync();

                        // 解码报告数据
                       // byte[] reportBytes = Convert.FromBase64String(result.ReportData);

                        // 调用打印（步骤5）
                        PrintLabel(reportBytes, ds);
                    }
                    else
                    {
                        MessageBox.Show("获取标签数据失败: " + response.ReasonPhrase);
                    }
                }
              
                // 调用 WebAPI
           
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误: " + ex.Message);
            }
        }


        private void PrintLabel(byte[] reportBytes, DataSet ds)
        {
            try
            {
                // 加载 FastReport
                using (var report = new Report())
                using (var ms = new MemoryStream(reportBytes))
                {
                    report.Load(ms);
                    report.Report.Dictionary.DataSources.Clear();
                    report.RegisterData(ds);
                    report.GetDataSource("BasBarcodeInfo").Enabled = true;
                    report.Refresh();
                    report.Prepare();
                    report.PrintSettings.ShowDialog = false;
                    report.PrintSettings.Copies = 1;
                    report.Print();
                    //PrintDialog printDialog = new PrintDialog();
                    //if (printDialog.ShowDialog() == DialogResult.OK)
                    //{
                    //    report.PrintSettings.ShowDialog = false;
                    //    report.PrintSettings.Copies = 1;
                    //    report.Print();
                    //}
      
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印失败: " + ex.Message);
                string tempFile = Path.Combine(Path.GetTempPath(), "debug_report.frx");
                File.WriteAllBytes(tempFile, reportBytes);
                MessageBox.Show($"报告已保存到: {tempFile}");
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                int byteRead = serialPort1.BytesToRead;
                byte[] arrData=new byte[byteRead];
                serialPort1.Read(arrData, 0, byteRead);

                if (arrData != null && arrData.Length > 3)
                {
                    string Data = string.Empty;
                    if (SerialData.IsBytesToString(arrData))
                    {
                        Data = SerialData.ToString(arrData);
                    }
                    else
                    {
                        Data = SerialData.ToHexString(arrData);
                    }
                    Data = Data.Replace("\0", "");
                    Data = Data.Replace("\n", "");
                    Data = Data.Replace("\r", "");
                    //  File.AppendAllText(Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt", Data);
              
                    string Code = Data.Replace(" ", "");
                    DataDelegate dataDelegate = null;
                    dataDelegate = new DataDelegate(GetRecod);
                    this.Invoke(dataDelegate, new object[] { arrData });


                }
            }

            catch 
            {


            }
        }

        private void FormMaterialCounting_FormClosing(object sender, FormClosingEventArgs e)
        {
            serialPort1.Close();
            serialPort1.Dispose();
        }
    }
}
